<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属题库" prop="belongingQuestionBank">
        <el-input
          v-model="queryParams.belongingQuestionBank"
          placeholder="请输入所属题库"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="test_paperList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="试题id" align="center" prop="testId" />
      <el-table-column label="所属题库" align="center" prop="belongingQuestionBank" />
      <el-table-column label="试题文件" align="center" prop="testFile" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['remove']"
          >删除</el-button>

          <el-button
            size="mini"
            type="text"
            icon="excel"
            @click="handleWordToExcel(scope.row)"
            v-hasPermi="['WordToExcel']"
          ><svg-icon icon-class="excel"/>下载Excel试题</el-button>

          <el-button
            size="mini"
            type="text"
            icon="excel"
            @click="modify_document(scope.row)"
          ><svg-icon icon-class="edit"/>修改文档格式</el-button>

          <el-button
            size="mini"
            type="text"
            icon="excel"
            @click="modify_document_template(scope.row)"
          ><svg-icon icon-class="edit"/>一键修改</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改试题对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属题库" prop="belongingQuestionBank">
          <el-input v-model="form.belongingQuestionBank" placeholder="请输入所属题库" />
        </el-form-item>
        <el-form-item label="试题文件" prop="testFile">
          <file-upload v-model="form.testFile"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改文档格式弹窗 -->
    <el-dialog
      width="30%"
      title="修改文档格式"
      :visible.sync="innerVisible"
      append-to-body center>
      <!-- 内层表单 -->
      <el-form :model="modify_document_form" :rules="modify_document_rules" ref="modify_document_form" status-icon>

        <!-- 正文格式提示 -->
        <div style="font-weight: bold;margin-top: 15px;margin-bottom: 12px">正文格式：</div>
        <el-form-item label="中文字体" :label-width="formLabelWidth" prop="chineseFontName">
          <el-select v-model="modify_document_form.chineseFontName" placeholder="中文字体">
            <el-option label="宋体" value="宋体"></el-option>
            <el-option label="仿宋_GB2312" value="仿宋_GB2312"></el-option>
            <el-option label="微软雅黑" value="微软雅黑"></el-option>
            <el-option label="楷体" value="楷体"></el-option>
            <el-option label="黑体" value="黑体"></el-option>
            <el-option label="隶书" value="隶书"></el-option>
            <el-option label="幼圆" value="幼圆"></el-option>
            <el-option label="华文行楷" value="华文行楷"></el-option>
            <el-option label="华文新魏" value="华文新魏"></el-option>
            <el-option label="华文琥珀" value="华文琥珀"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="英文字体" :label-width="formLabelWidth" prop="fontName">
          <el-select v-model="modify_document_form.fontName" placeholder="英文字体">
            <el-option label="Arial" value="Arial"></el-option>
            <el-option label="Times New Roman" value="Times New Roman"></el-option>
            <el-option label="Verdana" value="Verdana"></el-option>
            <el-option label="Helvetica" value="Helvetica"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="字号大小" :label-width="formLabelWidth" prop="fontSize">
          <el-select v-model="modify_document_form.fontSize" placeholder="字号大小">
            <el-option :label="item.name" :value="item.numw" :key="item.id" v-for="item in EmWight"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="行间距类型" :label-width="formLabelWidth" prop="lineSpacingRule">
          <el-select v-model="modify_document_form.lineSpacingRule" placeholder="行间距类型" @change="clearLineSpacingOption">
            <el-option label="特定倍数行距" value="0"></el-option>
            <el-option label="固定值(磅)" value="1"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="行间距" :label-width="formLabelWidth" prop="lineSpacing">
          <el-select v-model="modify_document_form.lineSpacing" placeholder="行间距" v-if="modify_document_form.lineSpacingRule === '0'">
            <el-option label="单倍行距" value="1"></el-option>
            <el-option label="1.5倍行距" value="1.5"></el-option>
            <el-option label="2倍行距" value="2"></el-option>
          </el-select>

          <el-input-number v-model="modify_document_form.lineSpacing" :min="0" label="行间距" v-if="modify_document_form.lineSpacingRule === '1'"></el-input-number>
        </el-form-item>

        <!-- 新增段落相关字段 -->
        <el-form-item label="段落前首行缩进" :label-width="formLabelWidth" prop="firstLineIndentChars">
          <el-input-number v-model="modify_document_form.firstLineIndentChars" :min="0" label="段落前首行缩进"></el-input-number>
        </el-form-item>

        <!-- 标题格式提示 -->
        <div style="font-weight: bold; margin-top: 25px;margin-bottom: 12px">标题格式：</div>
        <!-- 新增标题相关字段 -->
        <el-form-item label="标题英文字体" :label-width="formLabelWidth" prop="headingFontName">
          <el-select v-model="modify_document_form.headingFontName" placeholder="标题英文字体">
            <el-option label="Arial" value="Arial"></el-option>
            <el-option label="Times New Roman" value="Times New Roman"></el-option>
            <el-option label="Verdana" value="Verdana"></el-option>
            <el-option label="Helvetica" value="Helvetica"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题中文字体" :label-width="formLabelWidth" prop="headingChineseFontName">
          <el-select v-model="modify_document_form.headingChineseFontName" placeholder="标题中文字体">
            <el-option label="宋体" value="宋体"></el-option>
            <el-option label="方正小标宋" value="方正小标宋"></el-option>
            <el-option label="微软雅黑" value="微软雅黑"></el-option>
            <el-option label="楷体" value="楷体"></el-option>
            <el-option label="黑体" value="黑体"></el-option>
            <el-option label="黑体" value="黑体"></el-option>
            <el-option label="隶书" value="隶书"></el-option>
            <el-option label="幼圆" value="幼圆"></el-option>
            <el-option label="华文行楷" value="华文行楷"></el-option>
            <el-option label="华文新魏" value="华文新魏"></el-option>
            <el-option label="华文琥珀" value="华文琥珀"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题字号大小" :label-width="formLabelWidth" prop="headingFontSize">
          <el-select v-model="modify_document_form.headingFontSize" placeholder="标题字号大小">
            <el-option :label="item.name" :value="item.numw"  :key="item.id" v-for="item in EmWight"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题行间距类型" :label-width="formLabelWidth" prop="headingLineSpacingRule">
          <el-select v-model="modify_document_form.headingLineSpacingRule" placeholder="标题行间距类型" @change="clearHeadingLineSpacingOption">
            <el-option label="特定倍数行距" value="0"></el-option>
            <el-option label="固定值(磅)" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题行间距" :label-width="formLabelWidth" prop="headingLineSpacing">
          <el-select v-model="modify_document_form.headingLineSpacing" placeholder="标题行间距" v-if="modify_document_form.headingLineSpacingRule === '0'">
            <el-option label="单倍行距" value="1"></el-option>
            <el-option label="1.5倍行距" value="1.5"></el-option>
            <el-option label="2倍行距" value="2"></el-option>
          </el-select>
          <el-input-number v-model="modify_document_form.headingLineSpacing" :min="0" label="标题行间距" v-if="modify_document_form.headingLineSpacingRule === '1'"></el-input-number>
        </el-form-item>
        <el-form-item label="标题首行缩进" :label-width="formLabelWidth" prop="headingFirstLineIndentChars">
          <el-input-number v-model="modify_document_form.headingFirstLineIndentChars" :min="0" label="标题首行缩进"></el-input-number>
        </el-form-item>
        <el-form-item label="标题自动换行" :label-width="formLabelWidth" prop="autoPageBreak">
          <el-radio-group v-model="modify_document_form.autoPageBreak">
            <el-radio :label="0">是</el-radio>
            <el-radio :label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="标题居中对齐" :label-width="formLabelWidth" prop="centerHeading">
          <el-radio-group v-model="modify_document_form.centerHeading">
            <el-radio :label="0">是</el-radio>
            <el-radio :label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="modify_document_cancel">取 消</el-button>
        <el-button type="primary" @click="modify_document_submit">确 定</el-button>
      </div>
    </el-dialog>




  </div>
</template>

<script>
import {
  addTest_paper,
  delTest_paper,
  download,
  getTest_paper,
  listTest_paper, modify_document, modify_document_template,
  updateTest_paper,
  WordToExcel
} from '@/api/generateTest/test_paper'
// import {ElLoading} from 'element-ui/types/loading'

export default {
  name: "Test_paper",
  data() {
    return {
      innerVisible: false, // 控制弹窗的显示与隐藏
      modify_document_form: {
        modify_document_fileId: '', // 被修改文档id
        fontName: '', // 英文字体
        chineseFontName: '', // 中文字体
        fontSize: '', // 字体大小
        lineSpacingRule:'1', // 行间距类型0->单倍行距、1.5倍行距、2倍行距、多倍行距；1->固定值（磅）
        lineSpacing: '', // 行间距 如果类型是0，则填1、1.5、2、多倍；如果为1则填磅数
        firstLineIndentChars: '2', // 段落前首行缩进多少 一般填2
        headingFontName: '', // 标题英文字体
        headingChineseFontName: '', // 标题中文字体
        headingFontSize: '', // 标题字体大小
        headingLineSpacingRule: '1', // 标题行间距类型
        headingLineSpacing: '', // 标题行间距
        headingFirstLineIndentChars: '0', // 标题前首行缩进多少 一般填0
        autoPageBreak: 0, // 标题是否自动换行 0是 1否
        centerHeading: 0, // 标题是否居中对齐 0是 1否
      },
      modify_document_rules:{
        autoPageBreak: [
          { required: true, message: "标题自动换行不能为空", trigger: "blur" }
        ],
        centerHeading: [
          { required: true, message: "标题居中对齐不能为空", trigger: "blur" }
        ]

      },
      // 正文字体大小
      EmWight:[
        { id: 1, name: '初号', numw: 42 },
        { id: 2, name: '小初', numw: 36 },
        { id: 3, name: '一号', numw: 26 },
        { id: 4, name: '小一', numw: 24 },
        { id: 5, name: '二号', numw: 22 },
        { id: 6, name: '小二', numw: 18 },
        { id: 7, name: '三号', numw: 16 },
        { id: 8, name: '小三', numw: 15 },
        { id: 9, name: '四号', numw: 14 },
        { id: 10, name: '小四', numw: 12 },
        { id: 11, name: '五号', numw: 10.5 },
        { id: 12, name: '小五', numw: 9 },
        { id: 13, name: '六号', numw: 7.5 },
        { id: 14, name: '小六', numw: 6.5 },
        { id: 15, name: '七号', numw: 5.5 },
        { id: 16, name: '八号', numw: 5 },
      ],
      formLabelWidth: '120px',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试题表格数据
      test_paperList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        belongingQuestionBank: null,
        testFile: null
      },
      filePath: "",
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        belongingQuestionBank: [
          { required: true, message: "所属题库不能为空", trigger: "blur" }
        ],
        testFile: [
          { required: true, message: "试题文件不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // lineSpacing重置选项
    clearLineSpacingOption(e){
      console.log(e);
      if(e === "0"){
        this.modify_document_form.lineSpacing = ''
      }else{
        this.modify_document_form.lineSpacing = ''
      }
    },
    clearHeadingLineSpacingOption(e){
      console.log(e);
      if(e === "0"){
        this.modify_document_form.headingLineSpacing = ''
      }else{
        this.modify_document_form.headingLineSpacing = ''
      }
    },
    /** 查询试题列表 */
    getList() {
      this.loading = true;
      listTest_paper(this.queryParams).then(response => {
        this.test_paperList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.test_paperList.forEach(item => {
          if (item.testFile != null) {
            // 截取文件名
            this.filePath = item.testFile.split('/').pop();
            item.testFile = this.filePath;
          }
        })
      });

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        testId: null,
        belongingQuestionBank: null,
        testFile: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.testId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加试题";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const testId = row.testId || this.ids
      getTest_paper(testId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改试题";
      });
    },
    /** WordToExcel下载 */
    handleWordToExcel(row) {
      const testId = row.testId || this.ids
      WordToExcel(testId).then(response => {
        this.$modal.msgSuccess("已开始下载文件，请稍等");
        // console.log(response)
        const filePath = response
        download(testId).then((response) => {
          this.handleDownload(response,filePath);
        }).catch((error) => {
          console.error("文件下载失败:", error);
          this.$modal.msgError("文件下载失败");
        });
      });

    },

    /** 提供下载链接 */
    handleDownload(blob,filePath) {
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      // 截取文件名
      const fileNameWithExt = filePath.split('/').pop(); // 或者使用 '\\'
      const fileNameWithoutTimestampAndExt = fileNameWithExt.split('_')[0];
      link.setAttribute('download', `${fileNameWithoutTimestampAndExt}_${new Date().getTime()}.xlsx`);
      this.$modal.msgSuccess("下载成功");
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },

    // 修改文档格式相关方法
    modify_document(row) {
      this.innerVisible = true;
      this.modify_document_form.modify_document_fileId = row.testId;
    },
    modify_document_cancel() {
      this.innerVisible = false;
      this.$refs.modify_document_form.resetFields();
    },

    modify_document_submit() {
      this.$refs['modify_document_form'].validate(valid => {
        if (valid) {
          // 检查并转换特定的键
          const keysToCheck = ['fontName', 'chineseFontName', 'fontSize','lineSpacing'];

          keysToCheck.forEach(key => {
            if (typeof this.modify_document_form[key] !== 'string') {
              this.modify_document_form[key] = String(this.modify_document_form[key]);
            }
          });
          this.$message.info('正在修改格式.....')

          modify_document(this.modify_document_form)
            .then(response => {
              this.handleModifyDocumentDownload(response);
              this.$message({
                message: '修改成功！',
                type: 'success'
              });
              this.modify_document_form.fontSize = this.modify_document_form.fontSize - 0
              // console.log("chenggong",this.modify_document_form);

            })
            .catch(error => {
              console.error('错误:', error);
              this.$message.error('修改失败！');
            });
        }
        console.log('提交的数据:',this.modify_document_form );
        this.innerVisible = false;
      });
    },

    // 一键修改文档
    modify_document_template(row) {
      const testId = row.testId || this.ids;
      this.$message.info('正在修改格式.....');
      modify_document_template(testId)
        .then(response => {
          this.handleModifyDocumentDownload(response);
          this.$message({
            message: '修改成功！',
            type: 'success'
          });
        })
        .catch(error => {
          console.error('错误:', error);
          this.$message.error('修改失败！');
        });
    },

    /** 提供下载链接 */
    handleModifyDocumentDownload(blob) {
      if (!blob) {
        this.$message.error('无法创建文件下载链接，请检查服务器返回的数据是否正确。');
        return;
      }

      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `修改格式后_${new Date().getTime()}.docx`);
      this.$modal.msgSuccess("下载成功");
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      // 清理资源
      window.URL.revokeObjectURL(url);
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.testId != null) {
            updateTest_paper(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTest_paper(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const testIds = row.testId || this.ids;
      this.$modal.confirm('是否确认删除试题编号为"' + testIds + '"的数据项？').then(function() {
        return delTest_paper(testIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('generateTest/test_paper/export', {
        ...this.queryParams
      }, `test_paper_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.excel-icon {
  margin-right: 4px;
}
</style>
